<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function monthly_report_list_page()
{
    @$output = drupal_render(drupal_get_form('monthly_report_list_form'));
    return $output;
}


function monthly_report_list_form($form, &$form_state)
{
    global $user;
    $init_year = !empty($form_state['values']['year']) ? $form_state['values']['year'] : "";
    $init_month = !empty($form_state['values']['month']) ? $form_state['values']['month'] : "";
    _insert_date_selection_form($form, $form_state, 5, $init_year, $init_month);
    $uid = $user->uid;
    $user_info = _get_user_info($uid);
    if (!empty($_GET['distributor_id'])) {
        $form_state['distributor_id'] = $_GET['distributor_id'];
    }
    if (empty($form_state['distributor_id'])) {
//        $distributor_options = array(
//            '' => '--经销商--',
//        );
//        if (isset($user_info['manager']) && $user_info['manager'] === '0') {//经理
//            $query = db_select('employee', 'e1');
//            $query->join('employee', 'e2', 'e2.manager_uid = e1.employee_id');
//            $query->condition('e1.department_id', 1, '=');
//            $query->condition('e2.department_id', 1, '=');
//            $query->condition('e1.employee_id', $uid, '=');
//            $query->join('salesman_distributor_map', 'sd', 'sd.salesman_id=e2.employee_id or sd.salesman_id =' . $uid);
//            $query->join('distributor', 'd', 'd.distributor_id = sd.distributor_id');
//            $query->leftJoin('distributor', 'D2', 'D2.parent_distributor_id = d.distributor_id');
//            $query->leftJoin('distributor', 'D3', 'D3.parent_distributor_id = D2.distributor_id');
//            $query->leftJoin('distributor', 'D4', 'D4.parent_distributor_id = D3.distributor_id');
//            $query->leftJoin('distributor', 'D5', 'D5.parent_distributor_id = D4.distributor_id');
//            $query->leftJoin('distributor', 'D6', 'D6.parent_distributor_id = D5.distributor_id');
//            $query->condition('d.level', 1, '=');
//            $query->addField('d', 'distributor_id ', 'distributor_id');
//            $query->addField('d', 'distributor_name', 'distributor_name');
//
//            $query->addField('D2', 'distributor_id ', 'one_distributor_id');
//            $query->addField('D2', 'distributor_name', 'one_distributor_name');
//
//            $query->addField('D3', 'distributor_id', 'two_distributor_id');
//            $query->addField('D3', 'distributor_name', 'two_distributor_name');
//
//            $query->addField('D4', 'distributor_id', 'three_distributor_id');
//            $query->addField('D4', 'distributor_name', 'three_distributor_name');
//
//            $query->addField('D5', 'distributor_id', 'four_distributor_id');
//            $query->addField('D5', 'distributor_name', 'four_distributor_name');
//
//            $query->addField('D6', 'distributor_id', 'five_distributor_id');
//            $query->addField('D6', 'distributor_name', 'five_distributor_name');
//            $result_records = $query->execute();
//        } else {//业务员
//            $query = db_select('employee', 'e1');
//            $query->condition('e1.department_id', 1, '=');
//            $query->condition('e1.employee_id', $uid, '=');
//            $query->join('salesman_distributor_map', 'sd', 'sd.salesman_id=e1.employee_id or sd.salesman_id =' . $uid);
//            $query->join('distributor', 'd', 'd.distributor_id = sd.distributor_id');
//            $query->leftJoin('distributor', 'D2', 'D2.parent_distributor_id = d.distributor_id');
//            $query->leftJoin('distributor', 'D3', 'D3.parent_distributor_id = D2.distributor_id');
//            $query->leftJoin('distributor', 'D4', 'D4.parent_distributor_id = D3.distributor_id');
//            $query->leftJoin('distributor', 'D5', 'D5.parent_distributor_id = D4.distributor_id');
//            $query->leftJoin('distributor', 'D6', 'D6.parent_distributor_id = D5.distributor_id');
//            $query->condition('d.level', 1, '=');
//            $query->addField('d', 'distributor_id ', 'distributor_id');
//            $query->addField('d', 'distributor_name', 'distributor_name');
//
//            $query->addField('D2', 'distributor_id ', 'one_distributor_id');
//            $query->addField('D2', 'distributor_name', 'one_distributor_name');
//
//            $query->addField('D3', 'distributor_id', 'two_distributor_id');
//            $query->addField('D3', 'distributor_name', 'two_distributor_name');
//
//            $query->addField('D4', 'distributor_id', 'three_distributor_id');
//            $query->addField('D4', 'distributor_name', 'three_distributor_name');
//
//            $query->addField('D5', 'distributor_id', 'four_distributor_id');
//            $query->addField('D5', 'distributor_name', 'four_distributor_name');
//
//            $query->addField('D6', 'distributor_id', 'five_distributor_id');
//            $query->addField('D6', 'distributor_name', 'five_distributor_name');
//            $result_records = $query->execute();
//        }
//        foreach ($result_records as $key => $value) {
//            if (!empty($value->five_distributor_id)) {
//                $distributor_options[$value->distributor_id] = "┅　" . $value->distributor_name;
//                $distributor_options[$value->one_distributor_id] = "　┅　" . $value->one_distributor_name;
//                $distributor_options[$value->two_distributor_id] = "　　┅　" . $value->two_distributor_name;
//                $distributor_options[$value->three_distributor_id] = "　　　┅　" . $value->three_distributor_name;
//                $distributor_options[$value->four_distributor_id] = "　　　　┅　" . $value->four_distributor_name;
//                $distributor_options[$value->five_distributor_id] = "　　　　　┅　" . $value->five_distributor_name;
//            } else if (!empty($value->four_distributor_id)) {
//                $distributor_options[$value->distributor_id] = "┅　" . $value->distributor_name;
//                $distributor_options[$value->one_distributor_id] = "　┅　" . $value->one_distributor_name;
//                $distributor_options[$value->two_distributor_id] = "　　┅　" . $value->two_distributor_name;
//                $distributor_options[$value->three_distributor_id] = "　　　┅　" . $value->three_distributor_name;
//                $distributor_options[$value->four_distributor_id] = "　　　　┅　" . $value->four_distributor_name;
//            } else if (!empty($value->three_distributor_id)) {
//                $distributor_options[$value->distributor_id] = "┅　" . $value->distributor_name;
//                $distributor_options[$value->one_distributor_id] = "　┅　" . $value->one_distributor_name;
//                $distributor_options[$value->two_distributor_id] = "　　┅　" . $value->two_distributor_name;
//                $distributor_options[$value->three_distributor_id] = "　　　┅　" . $value->three_distributor_name;
//            } else if (!empty($value->two_distributor_id)) {
//                $distributor_options[$value->distributor_id] = "┅　" . $value->distributor_name;
//                $distributor_options[$value->one_distributor_id] = "　┅　" . $value->one_distributor_name;
//                $distributor_options[$value->two_distributor_id] = "　　┅　" . $value->two_distributor_name;
//            } else if (!empty($value->one_distributor_id)) {
//                $distributor_options[$value->distributor_id] = "┅　" . $value->distributor_name;
//                $distributor_options[$value->one_distributor_id] = "　┅　" . $value->one_distributor_name;
//            } else {
//                $distributor_options[$value->distributor_id] = "┅　" . $value->distributor_name;
//            }
//        }
//
//        if (isset($form_state['values']['distributor'])) {
//            if (!isset($distributor_options[$form_state['values']['distributor']])) {
//                $form_state['values']['distributor'] = '';
//            }
//        }
//        $form['distributor'] = _insert_login_salesman_distributor_selection_form($form, $form_state, $uid, !empty($record) ? $record->distributor_id : '');
        $form['address_distributor_markup']['#markup'] = '<div class="address-distributor-search">';
        $form['address_distributor'] = _insert_address_distributor_selection_form($form, $form_state, 'address_distributor');
        $form['address_distributor_markup_close']['#markup'] = '</div>';
    } else {
        $form['#distributor_id'] = $form_state['distributor_id'];
        $res = get_info($form['#distributor_id'], 'distributor');
        $form['#distributor_name'] = $res[0]->distributor_name;
//        $addr_red = get_all_addrname($res[0]->addr_id);
//        $province = $addr_red[0]->province?$addr_red[0]->province:"";
//        $city = $addr_red[0]->city? '  '.$addr_red[0]->city:"";
//        $county = $addr_red[0]->county? '  '.$addr_red[0]->county:"";
//        $town = $addr_red[0]->town? '  '.$addr_red[0]->town:"";
//        $village = $addr_red[0]->village? '  '.$addr_red[0]->village:"";
//        $form['#farmer_addr'] =$province.$city.$county.$town.$village;
    }
    $fields = array(
        '' => '请选择',
        'this_month_received_payment' => '当月回款',
        'accounts_receivable' => '应收账款',
        'payment_credit' => '信用占款',
        'paulin_number' => '篷布到期未返还数量',
    );
    numerical_range_search($form, $fields);
    $form['employee_salesman'] = get_all_salesman();
    if (get_user_role_name($user->uid) === 'administrator') {

    } else {
        $form['employee_list'] = _insert_loginuser_choose_salesman_selection($user);
    }
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}


function monthly_report_list_form_validate($form, &$form_state)
{
}

function data_list_view_page($form = '', &$form_state = '')
{
    global $user;
    $user_info = _get_user_info();
    $output = '';
    $query = db_select('distributor', 'D')->extend('PagerDefault')->extend('TableSort');
    $query->join('monthly_report', 'M', 'M.distributor_id=D.distributor_id');

    $query->fields('M', array('monthly_report_id', 'year', 'month', 'this_month_received_payment', 'accounts_receivable', 'author_uid'));
    $query->addField('D', 'distributor_name');
//        $query->join('employee','EM','M.author_uid= EM.employee_id');
//        $query->addField('EM', 'employee_name');  //暂时不与
    $query->addField('D', 'distributor_id');
    $query->join('addr', 'da', 'da.addr_id=D.addr_id');
    $query->leftJoin('addr', 'A', 'A.addr_id=da.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    if (!empty($form_state['values']['county'])) {//县级
        $query->condition('da.county_id', $form_state['values']['county'], '=');
    } elseif (!empty($form_state['values']['city'])) {//市级
        $query->condition('da.city_id', $form_state['values']['city'], '=');
    } elseif (!empty($form_state['values']['province'])) {//省级
        $query->condition('da.province_id', $form_state['values']['province'], '=');
    }
    if (!empty($form_state['values']['distributor'])) {//查询条件
        if ($form_state['values']['distributor']) {
            $query->condition('D.distributor_name', '%'.db_like($form_state['values']['distributor']).'%', 'LIKE');
        }
    } elseif (!empty($form_state['values']['salesman'])) {
        if ($form_state['values']['salesman']) {
            $query->join('salesman_distributor_map', 'sd', 'sd.distributor_id = D.distributor_id');
            $query->condition('sd.salesman_id', $form_state['values']['salesman'], '=');
        }
    } elseif (!empty($form_state['values']['juris'])) {
        if ($form_state['values']['juris']) {
            $query->join('salesman_distributor_map', 'SD', 'SD.distributor_id = D.distributor_id');
            $query->join('employee', 'E', 'E.employee_id = SD.salesman_id');
            $query->condition('E.juris_id', $form_state['values']['juris'], '=');
        }
    }
    if (!empty($form_state['values']['year'])) {//查询条件
        if ($form_state['values']['year']) {
            $query->condition('M.year', $form_state['values']['year'], '=');
        }
    }
    if (!empty($form_state['values']['month'])) {//查询条件
        if ($form_state['values']['month']) {
            $query->condition('M.month', $form_state['values']['month'], '=');
        }
    }

    salesman_distributor_role_relate_query_info($form_state,$query,'view all monthly_report','view own monthly_report','M');

    if (!empty($form_state['values']['employee_list']) && $form_state['values']['employee_list'] != "default") {//查询条件
        if ($form_state['values']['employee_list']) {
            $query->condition('M.author_uid', $form_state['values']['employee_list']);
        }
    }

    if (empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('M.timestamp', 'DESC');
    }
    if (!empty($form_state['values']['employee_salesman'])) {
        $query->condition('M.author_uid', $form_state['values']['employee_salesman'], '=');
    }
    if (!empty($form_state['values']['field'])) {
        if (!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])) {
            $db_and = db_and();
            $db_and->condition('M.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
            $db_and->condition('M.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($form_state['values']['min_number'])) {
            $query->condition('M.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
        } elseif (!empty($form_state['values']['max_number'])) {
            $query->condition('M.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
        }
    }
    if (!empty($form_state['distributor_id'])) {
        $query->condition('D.distributor_id', $form_state['distributor_id']);
    }
    $query->limit(variable_get("list_page_item_number", 5));
    //表头
    $header = array(
        array('data' => '选择', 'class' => ['essential no']),
        isset($form_state['distributor_id']) && !empty($form_state['distributor_id']) ? "" :
            array('data' => '经销商', 'class' => ['essential distributor']),
        array('data' => '年份', 'class' => ['integrant essential year'], 'field' => 'year'),
        array('data' => '月份', 'class' => ['essential month']),
        array('data' => '当月回款', 'class' => ['integrant essential this_month_received_payment'], 'field' => 'this_month_received_payment'),
        array('data' => '应收账款', 'class' => ['essential accounts_receivable']),
        array('data' => '操作', 'class' => ['essential more']),
    );
    $monthly_reportInfo = $query->orderByHeader($header)->execute();
    $rows = array();
    //表内容
    $n = 1;
    foreach ($monthly_reportInfo as $row) {
        if (nonghua_user_access('monthly_report', 'delete', $row->monthly_report_id, $row->author_uid, 0)) {
            $disabled = ' class="listViewTableCheck" ';
        } else {
            $disabled = ' disabled="true" ';
        }
        $rows[] = array(
            array('data' => '<input type="checkbox"' . $disabled . ' value ="' . $row->monthly_report_id . '"/>' . $n++, 'class' => ['integrant essential no']),
            isset($form_state['distributor_id']) && !empty($form_state['distributor_id']) ? "" :
                array('data' => '<a href="' . base_path() . 'distributor/edit/' . $row->distributor_id . '?distributor_id=' . $row->distributor_id . '" data-toggle="modal" target = "_self">' . $row->distributor_name . '</a>', 'class' => ['integrant essential monthly_report_id']),
            array('data' => $row->year, 'class' => ['integrant goRight essential year']),
            array('data' => $row->month, 'class' => ['integrant goRight essential month']),
            array('data' => $row->this_month_received_payment, 'class' => ['integrant haveTobr essential this_month_received_payment']),
            array('data' => $row->accounts_receivable, 'class' => ['essential accounts_receivable']),
            isset($form_state['distributor_id']) && !empty($form_state['distributor_id']) ?
                array('data' => '<a href="' . base_path() . 'sales/monthly_report/edit/' . $row->monthly_report_id . '?distributor_id=' . $form_state['distributor_id'] . '" data-toggle="modal" target = "_top"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more') :
                array('data' => '<a href="' . base_path() . 'sales/monthly_report/edit/' . $row->monthly_report_id . '" data-toggle="modal" target = "_top"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
        );
    }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && (user_access('delete own monthly_report') || user_access('delete all monthly_report'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    $output .= '<a href="'.base_path().'sales/monthly_report/export?distributor='.$form_state['valuse']['distributor'].'&year='.$form_state['values']['year'].'&month='.$form_state['values']['month'].'&employee_salesman='.$form_state['valuse']['employee_salesman'].'&field='.$form_state['values']['field'].'&min_number='.$form_state['values']['min_number'].'&max_number='.$form_state['values']['max_number'].'" data-toggle="modal" class="btn btn-mini">导出</a>';
    $output .= theme('pager');
    return $output;
}

function monthly_report_delete()
{
    ajax_table_delete('monthly_report', 'monthly_report_id');
}

function monthly_report_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $tableheader = array('经销商','年份','月份','当月回款','应收账款','逾期时间','信用占款','篷布到期未返还数量','篷布逾期时间','受损信息','各经销商应收账款及到期篷布明细及管控措施','促销执行情况','不合格信息通报','意外/事故信息','未解决事宜','竞争者信息','下个月任务');
    $data = get_monthly_report_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'销售数据');
}

function get_monthly_report_data($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('distributor', 'D');
    $query->join('monthly_report', 'M', 'M.distributor_id=D.distributor_id');

    $query->addField('D', 'distributor_name');
    $query->fields('M', array('year', 'month', 'this_month_received_payment', 'accounts_receivable','payment_overdue','payment_credit', 'paulin_number', 'paulin_overdue', 'damage_info', 'payment_info', 'promotion_info', 'unqualified_info', 'accident_info', 'pending_issues', 'competitor_info', 'next_month_task'));
    $query->join('addr', 'da', 'da.addr_id=D.addr_id');
    $query->leftJoin('addr', 'A', 'A.addr_id=da.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    if (!empty($form_state['values']['county'])) {//县级
        $query->condition('da.county_id', $form_state['values']['county'], '=');
    } elseif (!empty($form_state['values']['city'])) {//市级
        $query->condition('da.city_id', $form_state['values']['city'], '=');
    } elseif (!empty($form_state['values']['province'])) {//省级
        $query->condition('da.province_id', $form_state['values']['province'], '=');
    }
    if (!empty($form_state['values']['distributor'])) {//查询条件
        if ($form_state['values']['distributor']) {
            $query->condition('D.distributor_name', '%'.db_like($form_state['values']['distributor']).'%', 'LIKE');
        }
    } elseif (!empty($form_state['values']['salesman'])) {
        if ($form_state['values']['salesman']) {
            $query->join('salesman_distributor_map', 'sd', 'sd.distributor_id = D.distributor_id');
            $query->condition('sd.salesman_id', $form_state['values']['salesman'], '=');
        }
    } elseif (!empty($form_state['values']['juris'])) {
        if ($form_state['values']['juris']) {
            $query->join('salesman_distributor_map', 'SD', 'SD.distributor_id = D.distributor_id');
            $query->join('employee', 'E', 'E.employee_id = SD.salesman_id');
            $query->condition('E.juris_id', $form_state['values']['juris'], '=');
        }
    }
    if (!empty($form_state['values']['year'])) {//查询条件
        if ($form_state['values']['year']) {
            $query->condition('M.year', $form_state['values']['year'], '=');
        }
    }
    if (!empty($form_state['values']['month'])) {//查询条件
        if ($form_state['values']['month']) {
            $query->condition('M.month', $form_state['values']['month'], '=');
        }
    }

    salesman_distributor_role_relate_query_info($form_state,$query,'view all monthly_report','view own monthly_report','M');

    if (!empty($form_state['values']['employee_list']) && $form_state['values']['employee_list'] != "default") {//查询条件
        if ($form_state['values']['employee_list']) {
            $query->condition('M.author_uid', $form_state['values']['employee_list']);
        }
    }

    if (empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('M.timestamp', 'DESC');
    }
    if (!empty($form_state['values']['employee_salesman'])) {
        $query->condition('M.author_uid', $form_state['values']['employee_salesman'], '=');
    }
    if (!empty($form_state['values']['field'])) {
        if (!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])) {
            $db_and = db_and();
            $db_and->condition('M.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
            $db_and->condition('M.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($form_state['values']['min_number'])) {
            $query->condition('M.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
        } elseif (!empty($form_state['values']['max_number'])) {
            $query->condition('M.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
        }
    }
    if (!empty($form_state['distributor_id'])) {
        $query->condition('D.distributor_id', $form_state['distributor_id']);
    }
    $monthly_reportInfo = $query->execute()->fetchAll();
//    foreach($monthly_reportInfo as $k => $v){
//        $invoiceInfo[$k]->province= $v->province.$v->city.$v->county;
//        unset($invoiceInfo[$k]->city);
//        unset($invoiceInfo[$k]->county);
//        $monthly_reportInfo[$k]->variety_name = $v->variety_name.$v->proportion.$v->SM;
//        unset($invoiceInfo[$k]->proportion);
//        unset($invoiceInfo[$k]->SM);
//    }
    return $monthly_reportInfo;
}